<template>
  <div class="innerWrapper">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="名称" prop="appName">
        <el-input v-model="ruleForm.appName"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="appDesc">
        <el-input type="textarea"  :autosize="{ minRows: 3 }" v-model="ruleForm.appDesc"></el-input>
      </el-form-item>
      <el-form-item label="上传图标" prop="icon">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="uploadHeader"
          :show-file-list="false"
          :on-success="handleIconSuccess"
          v-loading="iconUploadLoading"
          :on-progress="iconUploadProgress"
          :before-upload="beforeIconUpload"
        >
          <img v-if="iconUrl" :src="iconUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input v-model="ruleForm.contact"></el-input>
      </el-form-item>
      <el-form-item label="上架模块" prop="typeId">
        <el-select @change="moduleChange" v-model="ruleForm.uploadModule" placeholder="请选择上架模块">
          <el-option label="工业APP" value="1"></el-option>
          <el-option label="工业微服务" value="2"></el-option>
          <el-option label="工业机理模型" value="3"></el-option>
        </el-select>
        <el-cascader
          :options="options"
          ref="cascader"
          v-model="ruleForm.typeId"
          style="margin-left:24px;width:300px;"
          :props="props"
          clearable
          @change="cascaderChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="使用场景" prop="usePlace" v-if="ruleForm.uploadModule!=='2'">
        <el-input type="textarea" :autosize="{ minRows: 3 }" v-model="ruleForm.usePlace"></el-input>
      </el-form-item>
      <el-form-item v-if="ruleForm.uploadModule!=='2'" label="上传文件" prop="file">
        <el-upload
          class="file-upload"
          ref="file-upload"
          :action="uploadUrl"
          :headers="uploadHeader"
          :multiple="false"
          :limit="1"
          :on-exceed="handleFileExceed"
          :file-list="fileList"
          :on-success="handleFileSuccess"
          v-loading="fileUploadLoading"
          :on-progress="fileUploadProgress"
          :before-upload="beforeFileUpload"
        >
          <el-button size="small" type="primary"> 上传文件 </el-button>
          <span style="margin-left: 20px;font-size: 12px; color: #606266">只能上传一个文件</span>
        </el-upload>
      </el-form-item>
      <div v-if="ruleForm.uploadModule === '2'">
        <el-form-item label="请求地址" prop="apiUrl">
          <el-input v-model="ruleForm.apiUrl" placeholder="请输入请求地址"></el-input>
        </el-form-item>
        <el-form-item label="请求方式" prop="reqMode">
          <el-select v-model="ruleForm.reqMode" placeholder="请选择请求方式">
            <el-option label="GET" value="0"></el-option>
            <el-option label="POST" value="1"></el-option>
            <el-option label="PUT"  value="2"></el-option>
            <el-option label="PATCH" value="3"></el-option>
            <el-option label="DELETE" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请求参数详情" prop="reqParams">
          <el-button @click="reqAddLine" size="small" type="primary">添加一行</el-button>
          <el-table :data="reqTableData" class="tableBorder">
            <el-table-column prop="reqParams.name" label="名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="reqParams.isRequired" label="必填">
              <template slot-scope="scope">
                <el-select v-model="scope.row.isRequired" placeholder="请选择">
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="reqParams.type" label="类型">
              <template slot-scope="scope">
                <el-select v-model="scope.row.type" placeholder="请选择">
                  <el-option label="INT" value="INT"></el-option>
                  <el-option label="BIGINT" value="BIGINT"></el-option>
                  <el-option label="CHAR" value="CHAR"></el-option>
                  <el-option label="VARCHAR" value="VARCHAR"></el-option>
                  <el-option label="TEXT" value="TEXT"></el-option>
                  <el-option label="BOOLEAN" value="BOOLEAN"></el-option>
                  <el-option label="FLOAT" value="FLOAT"></el-option>
                  <el-option label="DATE" value="DATE"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="reqParams.comment" width="350" label="说明">
              <template slot-scope="scope">
                <el-input placeholder="请输入内容" v-model="scope.row.comment"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="90">
              <template slot-scope="scope">
                <i
                  style="cursor:pointer"
                  @click="deleteRow('reqTableData',scope)"
                  class="el-icon-delete"
                ></i>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="请求示例" prop="reqSample">
          <el-input v-model="ruleForm.reqSample" placeholder="请输入请求示例"></el-input>
        </el-form-item>
        <el-form-item label="返回参数详情" prop="resParams">
          <el-button @click="resAddLine" size="small" type="primary">添加一行</el-button>
          <el-table :data="resTableData" class="tableBorder">
            <el-table-column prop="resParams.name" label="名称">
              <template slot-scope="scope">
                <el-input placeholder="请输入内容" v-model="scope.row.name"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="resParams.type" label="类型">
              <template slot-scope="scope">
                <el-select v-model="scope.row.type" placeholder="请选择">
                  <el-option label="INT" value="INT"></el-option>
                  <el-option label="BIGINT" value="BIGINT"></el-option>
                  <el-option label="CHAR" value="CHAR"></el-option>
                  <el-option label="VARCHAR" value="VARCHAR"></el-option>
                  <el-option label="TEXT" value="TEXT"></el-option>
                  <el-option label="BOOLEAN" value="BOOLEAN"></el-option>
                  <el-option label="FLOAT" value="FLOAT"></el-option>
                  <el-option label="DATE" value="DATE"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="resParams.comment" label="说明">
              <template slot-scope="scope">
                <el-input placeholder="请输入内容" v-model="scope.row.comment"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="90">
              <template slot-scope="scope">
                <i
                  style="cursor:pointer"
                  @click="deleteRow('resTableData',scope)"
                  class="el-icon-delete"
                ></i>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="返回示例" prop="resSample">
          <el-input v-model="ruleForm.resSample" placeholder="请输入返回示例"></el-input>
        </el-form-item>
        <el-form-item label="返回类型" prop="resType">
          <el-input v-model="ruleForm.resType" placeholder="请输入返回类型"></el-input>
        </el-form-item>
      </div>
      <el-form-item label="是否公开" prop="isPrivate">
        <el-switch v-model="ruleForm.isPrivate"></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button @click="() => $router.go(-1)">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  data() {
    const that = this
    var validateSpacial = (rule, value, callback) => {
      const reg = new RegExp(/^[\w\u4e00-\u9fa5]+$/)
      if (!reg.test(value)) {
        callback(new Error('只能输入汉字、字母、下划线和数字的组合'))
      }
      callback()
    }
    return {
      options: [],
      props: {
        lazy: true,
        checkStrictly: false,
        expandTrigger: 'hover',
        async lazyLoad(node, resolve) {
          if (!node) {
            return
          }
          const { value, level } = node
          if (level === 2) {
            resolve()
            return
          }
          // 不选择模块，不加载数据
          if (that.ruleForm.uploadModule === '') {
            return false
          }
          const data = await that.$store.dispatch('shelves/getFilters', {
            params: {
              parentId: value
            },
            type: that.ruleForm.uploadModule
          })
          resolve(data)
        }
      },
      uploadUrl: '/hanyun/file-service/minio/upload',
      iconUrl: '',
      fileUrl: '',
      fileName: '',
      fileList: [],
      typeId: '',
      iconUploadLoading: false,
      fileUploadLoading: false,
      reqTableData: [],
      resTableData: [],
      ruleForm: {
        appName: '',
        resSample: '',
        reqSample: '',
        usePlace: '',
        appDesc: '',
        icon: '',
        apiUrl: '',
        contact: '',
        file: '',
        uploadModule: '',
        reqParams: [],
        resParams: [],
        isPrivate: true,
        reqMode: '',
        resType: '',
        secretkey: '',
        typeId: ''
      },
      rules: {
        appName: [
          { required: true, message: '请输入应用名称', trigger: 'blur' },
          { validator: validateSpacial, trigger: 'blur' },
          { max: 60, message: '应用名称不能超过60个字符' }
        ],
        usePlace: [
          { required: true, message: '请输入使用场景', trigger: 'blur' }
        ],
        appDesc: [
          { required: true, message: '请输入应用介绍', trigger: 'blur' }
        ],
        icon: [],
        apiUrl: [
          { required: true, message: '请输入请求地址', trigger: 'blur' },
          { max: 60, message: '请求地址不能超过60个字符' }
        ],
        typeId: [
          { required: true, message: '请完整选择上架模块', trigger: 'submit' }
        ],
        resType: [
          { required: true, message: '请输入返回类型', trigger: 'blur' },
          { max: 50, message: '不能超过50个字符' }
        ],
        contact: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { max: 60, message: '不能超过60个字符' }
        ],
        file: [
          { required: true, message: '请上传文件', trigger: 'blur' }
        ],
        reqMode: [
          {
            required: true,
            message: '请输入请求方式',
            trigger: 'change'
          }
        ],
        reqSample: [],
        resSample: [],
        uploadModule: [
          {
            required: true,
            message: '请选择上架模块',
            trigger: 'change'
          }
        ],
        reqParams: [],
        resParams: [],
        isPrivate: []
      }
    }
  },
  created() {
    if (Object.keys(this.editData).length > 0) {
      this.ruleForm.id = this.editData.id
      this.ruleForm.appName = this.editData.name
      this.ruleForm.usePlace = this.editData.usePlace
      this.ruleForm.appDesc = this.editData.description
      this.ruleForm.apiUrl = this.editData.apiUrl
      this.ruleForm.icon = this.editData.iconUrl
      this.iconUrl = this.editData.iconUrl
      this.ruleForm.contact = this.editData.contact
      this.ruleForm.uploadModule = this.editType
      if (this.editData.fileName && this.editData.fileUrl) {
        const fileName = this.editData.fileName.slice(this.editData.fileName.lastIndexOf('/') + 1)
        this.fileList = [{ name: fileName, url: this.editData.fileUrl }]
      }
      this.fileName = this.editData.fileName
      this.fileUrl = this.editData.fileUrl
      this.ruleForm.file = this.editData.fileUrl
      this.ruleForm.reqMode = '' + this.editData.reqMode || ''
      // 级联绑定的为一个数组
      this.ruleForm.typeId = this.editData.typeIds.split(',')
      this.ruleForm.reqParams = JSON.parse(JSON.stringify(this.editData.reqParam || []))
      this.reqTableData = JSON.parse(JSON.stringify(this.editData.reqParam || []))
      this.ruleForm.resParams = JSON.parse(JSON.stringify(this.editData.resParam || []))
      this.resTableData = JSON.parse(JSON.stringify(this.editData.resParam || []))
      this.ruleForm.reqSample = this.editData.reqSample
      this.ruleForm.resSample = this.editData.resSample
      this.ruleForm.resType = this.editData.resType
      this.ruleForm.isPrivate = this.editData.openFlag === 1
    }
  },
  watch: {
    'ruleForm.uploadModule': {
      handler(v) {
        if (Object.keys(this.editData).length === 0) {
          this.options = []
        }
      }
    }
  },
  computed: {
    ...mapState({
      uploadHeader: (state) => state.shelves.uploadHeader,
      editData: state => state.detail.detailInfo,
      editType: state => state.shelves.editType
    })
  },
  methods: {
    cascaderChange(v, a) {
      if (!v || v.length === 0) {
        // this.$store.commit('home/setFilterId', {})
        // this.getList()
        return
      }
      if (v.length === 1) {
        if (
          this.ruleForm.uploadModule === '1' ||
          this.ruleForm.uploadModule === '3'
        ) {
          this.filterId = {
            typeIds: this.$refs.cascader.getCheckedNodes()[0].data.id
          }
        } else {
          this.filterId = { parentId: v[0] }
        }
      } else {
        this.filterId = { typeIds: v[1] }
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 新增
          if (Object.keys(this.editData).length === 0) {
            this.$store
              .dispatch('shelves/shelveGoods', {
                type: this.ruleForm.uploadModule,
                params: {
                  accesskey: Math.random()
                    .toString()
                    .substring(2),
                  apiUrl: this.ruleForm.apiUrl,
                  usePlace: this.ruleForm.usePlace,
                  description: this.ruleForm.appDesc,
                  name: this.ruleForm.appName,
                  openFlag: this.ruleForm.isPrivate === true ? '1' : '0',
                  publisher: this.$store.state.login.loginInfo.id,
                  contact: this.ruleForm.contact,
                  reqMode: this.ruleForm.reqMode,
                  reqParam: this.ruleForm.reqParams,
                  reqSample: this.ruleForm.reqSample,
                  resParam: this.ruleForm.resParams,
                  resSample: this.ruleForm.resSample,
                  resType: this.ruleForm.resType,
                  secretkey: this.ruleForm.secretkey,
                  status: 0,
                  typeId: this.ruleForm.typeId.pop(),
                  fileName: this.fileName,
                  fileUrl: this.ruleForm.file,
                  iconUrl: this.ruleForm.icon
                }
              })
              .then((result) => {
                this.$message({
                  message: result,
                  type: 'success'
                })
                if (this.ruleForm.uploadModule !== '2') {
                  this.$refs['file-upload'].clearFiles()
                }
                this.ruleForm = {
                  uploadModule: '',
                  isPrivate: true,
                  file: ''
                }
                this.iconUrl = ''
                this.fileUrl = ''
              })
              .catch((err) => {
                this.$message({
                  message: err,
                  type: 'error'
                })
              })
          // 修改
          } else {
            this.$store.dispatch('shelves/updateShelvesGoods', {
              type: this.ruleForm.uploadModule,
              params: {
                accesskey: '',
                id: this.ruleForm.id,
                apiUrl: this.ruleForm.apiUrl,
                usePlace: this.ruleForm.usePlace,
                description: this.ruleForm.appDesc,
                name: this.ruleForm.appName,
                openFlag: this.ruleForm.isPrivate === true ? '1' : '0',
                publisher: this.$store.state.login.loginInfo.id,
                contact: this.ruleForm.contact,
                reqMode: this.ruleForm.reqMode,
                reqParam: this.ruleForm.reqParams,
                reqSample: this.ruleForm.reqSample,
                resParam: this.ruleForm.resParams,
                resSample: this.ruleForm.resSample,
                resType: this.ruleForm.resType,
                secretkey: this.ruleForm.secretkey,
                status: 0,
                typeId: this.ruleForm.typeId.pop(),
                fileName: this.fileName,
                fileUrl: this.ruleForm.file,
                iconUrl: this.ruleForm.icon
              }
            }).then(result => {
              this.$message({
                message: result,
                type: 'success'
              })
              this.$store.commit('detail/setDetailInfo', {})
              if (this.ruleForm.uploadModule !== '2') {
                this.$refs['file-upload'].clearFiles()
              }
              this.ruleForm = {
                uploadModule: '',
                isPrivate: true,
                file: ''
              }
              this.iconUrl = ''
              this.fileUrl = ''
              this.fileList = []
              this.$router.push('/main/personalInfo')
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleIconSuccess(res, file) {
      this.iconUploadLoading = false
      this.iconUrl = URL.createObjectURL(file.raw)
      this.ruleForm.icon = res.result.url
    },
    handleFileSuccess(res, file) {
      this.fileUploadLoading = false
      this.fileUrl = URL.createObjectURL(file.raw)
      this.ruleForm.file = res.result.url
      this.fileName = res.result.fileName
    },
    handleFileExceed() {
      this.$message({
        message: '只能上传一个文件',
        type: 'warning'
      })
    },
    iconUploadProgress() {
      this.iconUploadLoading = true
    },
    fileUploadProgress() {
      this.fileUploadLoading = true
    },
    beforeIconUpload(file) {
      const isPic = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isPic) {
        this.$message.error('图片格式必须为jpeg、jpg、png')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return isPic && isLt2M
    },
    beforeFileUpload(file) {
      //   const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },
    moduleChange(v) {
      this.ruleForm.uploadModule = v
    },
    reqAddLine() {
      const item = {
        id: Math.random()
          .toString()
          .substring(2)
      }
      this.reqTableData.push(item)
      this.ruleForm.reqParams.push(item)
    },
    resAddLine() {
      const item = {
        id: Math.random()
          .toString()
          .substring(2)
      }
      this.resTableData.push(item)
      this.ruleForm.resParams.push(item)
    },
    deleteRow(deleteFrom, row) {
      this[deleteFrom].splice(
        this[deleteFrom].findIndex((item) => item.id === row.row.id),
        1
      )
      if (deleteFrom === 'reqTableData') {
        this.ruleForm.reqParams = [...this[deleteFrom]]
      } else {
        this.ruleForm.resParams = [...this[deleteFrom]]
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.innerWrapper {
  width: 78vw;
  margin: 0 auto;
}
/deep/ .el-table .el-select {
  width: 100%;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/ .avatar-uploader {
  width: 10vw;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.tableBorder {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  margin-top: 10px;
}
/deep/ .el-table::before {
  background-color: #fff;
}
</style>
